package com.rgs.gateway.starter.config;


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rgs.gateway.starter.entity.RedisUser;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.support.RedisRepositoryFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;

/**
 * @author RenGaoshuai
 * @date 2024/6/27 15:30
 * @description 自定义的redis自动配置类
 */
@Configuration
@ConditionalOnProperty(prefix = "spring.redis", name = "enable", havingValue = "true")
@AutoConfigureAfter(RedisRepositoryFactory.class)
public class MyRedisAutoConfig {

    private static final Jackson2JsonRedisSerializer REDIS_VALUE_SERIALIZER = new Jackson2JsonRedisSerializer(Object.class);
    private static final RedisSerializer<String> REDIS_KEY_SERIALIZER = new StringRedisSerializer();

    static {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        REDIS_VALUE_SERIALIZER.setObjectMapper(objectMapper);
    }

    @Resource
    RedisConnectionFactory connectionFactory;

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        //key
        redisTemplate.setKeySerializer(REDIS_KEY_SERIALIZER);
        redisTemplate.setHashKeySerializer(REDIS_KEY_SERIALIZER);
        //value
        redisTemplate.setValueSerializer(REDIS_VALUE_SERIALIZER);
        redisTemplate.setHashValueSerializer(REDIS_VALUE_SERIALIZER);

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }


    @Bean
    public RedisUser redisUser(){
        System.out.println("初始化RedisUser对象成功");
        return new RedisUser();
    }

}
